package com.property.manage.service.owner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guardchina.framework.mybatis.model.CustomPage;
import com.guardchina.framework.util.exception.BusinessException;
import com.guardchina.framework.util.utils.ExcelUtil;
import com.guardchina.framework.util.utils.PhoneUtil;
import com.property.manage.dao.owner.OwnerMapper;
import com.property.manage.model.owner.OwnerCountVo;
import com.property.manage.model.owner.OwnerEntity;
import com.property.manage.model.owner.OwnerVo;
import com.property.manage.model.resource.Building;
import com.property.manage.service.resource.BuildingService;
import com.property.manage.util.ExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/7/15
 */
@Component
@Slf4j
public class OwnerService {
    @Autowired
    private OwnerMapper ownerMapper;
 @Autowired
 private BuildingService buildingService;

    public OwnerEntity findById(Integer id) {
        return ownerMapper.selectById(id);
    }

    public OwnerEntity findByBuildingId(Integer buildingId){
        QueryWrapper<OwnerEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("building_id", buildingId);

        return ownerMapper.selectOne(wrapper);
    }

    public CustomPage<OwnerVo> ownerPage(Long pageNo, Long pageSize, String name,
                                            String phone,Integer quarterId,Integer type,Integer building,
                                         Integer unit,String roomNumber) {

        Page<OwnerVo> page = new Page<>(pageNo, pageSize);
        IPage<OwnerVo> village = ownerMapper.getOwner(page,name,quarterId,phone,type,building, unit, roomNumber);
        return new CustomPage<>(village);
    }

    public boolean checkName(String ownerName,Integer buildingId){
        QueryWrapper<OwnerEntity> qw=new QueryWrapper<>();
        qw.eq("owner_name",ownerName);
        qw.eq("building_id",buildingId);
        return ownerMapper.selectOne(qw)!=null;
    }

    public void add(String ownerName, Integer type, String phone, Integer buildingId) {
        OwnerEntity ownerEntity = new OwnerEntity();
        ownerEntity.setBuildingId(buildingId);
        ownerEntity.setOwnerName(ownerName);
        ownerEntity.setType(type);
        if (checkName(ownerName,buildingId)){
            throw new BusinessException("该业主信息以及登记",String.format("业主名称[%s],楼栋id[%s]",phone,buildingId));
        }
        //手机加验证
        if (!PhoneUtil.isMobile(phone)){
            throw new BusinessException("请输入正确的手机号码",String.format("手机号码错误[%s]",phone));
        }
        ownerEntity.setPhone(phone);
        ownerMapper.insert(ownerEntity);
    }

    public void update(Integer id,String ownerName, Integer type, String phone, Integer buildingId) {
        OwnerEntity ownerEntity = this.findById(id);
        if (!ownerEntity.getOwnerName().equals(ownerEntity.getOwnerName()) || buildingId!=ownerEntity.getBuildingId()){
            if (checkName(ownerName,buildingId)){
                throw new BusinessException("该业主信息已经登记",String.format("业主名称[%s],楼栋id[%s]",ownerName,buildingId));
            }
        }
        UpdateWrapper<OwnerEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("owner_name", ownerName);
        wrapper.set("type", type);
        wrapper.set(PhoneUtil.isMobile(phone),"phone", phone);
        wrapper.set("building_id",buildingId);
        wrapper.eq("id",id);
        ownerMapper.update(null,wrapper);
    }

    public void delete(Integer id) {
        ownerMapper.deleteById(id);
    }

    public OwnerCountVo findCount(Integer quarterId){
        OwnerCountVo ownerCountVo = new OwnerCountVo();
        ownerCountVo.setTotal(ownerMapper.getOwnerCount(null,quarterId));
        ownerCountVo.setOwnerTotal(ownerMapper.getOwnerCount(1,quarterId));
        ownerCountVo.setTenantTotal(ownerMapper.getOwnerCount(2,quarterId));
        return ownerCountVo;
    }

    /**
     * 下载导入模板
     * @param request
     * @param response
     */
    public void downOwner(HttpServletRequest request, HttpServletResponse response) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("业主信息导入模板");
        //创建第一行
        XSSFRow row = sheet.createRow(0);
        //设置表头格式
        List<String> titles = Arrays.asList("楼栋","单元","房号","业主名称","类型(业主/租户)","手机号码");
        for (int i = 0; i <titles.size(); i++) {
            sheet.setColumnWidth(i, 4500);
            row.createCell(i).setCellValue(titles.get(i));
        }

        String fileName = "业主信息导入模板.xlsx";

        ExportUtil.exportExcel(request, response, fileName, workbook);

    }

    /**
     * 批量导入
     * @param file
     * @param quarterId
     */
  public void uploading(MultipartFile file,Integer quarterId) throws IOException {
      Workbook workbook = null;
      //项目对象集合
      List<OwnerEntity> projectVos = new ArrayList<>();
      List<Integer> buildingIds = new ArrayList<>();
      boolean excel2003 = ExcelUtil.isExcel2003(file.getOriginalFilename());
      if (excel2003) {
          workbook = new HSSFWorkbook(file.getInputStream());
      } else {
          //获取excel文件的io流
          workbook = new XSSFWorkbook(file.getInputStream());
      }
      //判断格式
      List<String> titles = Arrays.asList("楼栋","单元","房号","业主名称","类型(业主/租户)","手机号码");
      Sheet sheet = workbook.getSheetAt(0);
      for (int i = 0; i <= 5; i++) {
          Row row = sheet.getRow(0);
          Cell cell = row.getCell(i);
          String s1 = cell.toString();
          String s = titles.get(i);
          if (!s.equals(s1)) {
              throw new BusinessException( "Excel表格第一行" + s1 + "名称错误");
          }
      }
      int num = sheet.getLastRowNum();

      for (int i = 1; i <= num; i++) {
          OwnerEntity ownerEntity = new OwnerEntity();
          Row row = sheet.getRow(i);
          if (row == null) {
              continue;
          }
          //过滤表格中的空格行
          boolean f = isF(row);
          if (f) {
              continue;
          }
          //设置楼栋
          Cell cell0 = row.getCell(0);
          //String building = ExcelUtil.checkValue(cell0);
          String building = (String) ExcelUtil.getCellValue(cell0);
          if ("".equals(building)){
              throw new BusinessException("第" + i + "行的楼栋不能为空");
          }
          //设置单元
          Cell cell1 = row.getCell(1);
          String unit= (String) ExcelUtil.getCellValue(cell1);
          if ("".equals(unit)){
              throw new BusinessException("第" + i + "行的单元不能为空");
          }

          //设置房号
          Cell cell3 = row.getCell(2);
          String roomNumber = (String) ExcelUtil.getCellValue(cell3);
          if ("".equals(roomNumber)){
              throw new BusinessException("第" + i + "行的房号不能为空");
          }
          //业主名称
          Cell cell4 = row.getCell(3);
          String ownerName = (String) ExcelUtil.getCellValue(cell4);
          if ("".equals(ownerName)){
              throw new BusinessException("第" + i + "行的业主名称不能为空");
          }
         ownerEntity.setOwnerName(ownerName);
          Cell cell5 = row.getCell(4);
          String type = (String) ExcelUtil.getCellValue(cell5);
          if ("".equals(type)){
              throw new BusinessException("第" + i + "行的业主类型不能为空");
          }
          if ("业主".equals(type)){
              ownerEntity.setType(1);
          }
          if ("租户".equals(type)){
              ownerEntity.setType(2);
          }
          Cell cell6 = row.getCell(5);
          //String phone = ExcelUtil.checkValue(cell6);
          String phone = (String) ExcelUtil.getCellValue(cell6);
          if ("".equals(phone)||!PhoneUtil.isMobile(phone)){
              throw new BusinessException("第" + i + "行的手机号码不正确");
          }
         ownerEntity.setPhone(phone);
          Building one = buildingService.findOne(quarterId, Integer.valueOf(building), Integer.valueOf(unit), roomNumber);
          if (one==null){
              throw new BusinessException("第" + i + "行的数据没有查到相关的楼栋信息");
          }
          ownerEntity.setBuildingId(one.getId());

          //去表格中重复的信息
          if (buildingIds.contains(one.getId())){
              throw new BusinessException("第" + i + "行的业主在表格中存在相同信息，请删除");
          }
          buildingIds.add(one.getId());
          //去数据库中的信息
          if (checkName(ownerName,one.getId())){
              throw new BusinessException("第" + i + "行的业主信息已经登记，请勿重复添加");
          }
          projectVos.add(ownerEntity);
      }
      if (projectVos.isEmpty()) {
          throw new BusinessException("文件中没有数据");
      }
      ownerMapper.saveList(projectVos);


  }

  public OwnerEntity findOneByBuildingId(Integer buildingId){
      QueryWrapper<OwnerEntity> wrapper = new QueryWrapper<>();
      wrapper.eq("building_id", buildingId);
      wrapper.last("limit 1");

      return ownerMapper.selectOne(wrapper);
  }


    /**
     * 判断某一行是否是空
     *
     * @param row
     * @return
     */
    private boolean isF(Row row) {
        boolean f = true;
        for (int j = 0; j <= 5; j++) {
            Cell cell = row.getCell(j);
            if (cell != null) {
                String value = ExcelUtil.checkValue(cell);
                if (!"".equals(value)) {
                    f = false;
                    break;
                }
            }
        }
        return f;
    }


    public OwnerVo getById(Integer id){
        return ownerMapper.getOwnerById(id);
    }

    public OwnerEntity findByBuilding(Integer building){
       QueryWrapper<OwnerEntity> qw=new QueryWrapper<>();
       qw.eq("building_id",building);
        List<OwnerEntity> list = ownerMapper.selectList(qw);
        if (list.isEmpty()){
            return new OwnerEntity();
        }
        return list.get(0);
    }
}
